<template>
    <Upload ref="upload" action="/api/upload/file" 
        :format="format"
        :on-format-error="handleFormatError"
        :default-file-list="defaultList" 
        :on-remove="handleRemove" 
        :on-success="handleSuccess"
        :max-size="1000000">
        <Button type="ghost" icon="ios-cloud-upload-outline" :disabled="buttonDisabled">上传文件</Button>
        <span style="color:#888">最多上传{{number}}个文件,文件格式为{{format}}</span>
    </Upload>
</template>
<script>
    export default {
        name: 'UploadedList',
        props: {
            value: {
                type: Array
            },
            format: {
                type: Array,
                default: ['jpg','jpeg','png','doc','docx','txt']
            },
            number: {
                type: Number,
                default: 5
            }
        },
        data () {
            return {
            }
        },
        computed: {
            defaultList() {
                return this.value;
            },
            buttonDisabled() {
                return this.value.length >= this.number;
            }
        },
        methods: {
            handleSuccess (res, file) {
                if(res.status == 10000) {
                    if(res.list.length > 0) this.value.push(res.list[0]);
                    this.$emit('add',this.value);
                }else {
                    this.$refs.upload.fileList.splice(this.$refs.upload.fileList.length-1, 1);
                    this.$Message.error(res.message);
                }
            },
            handleRemove (file) {
                const fileList = this.$refs.upload.fileList;
                var index = fileList.indexOf(file);
                this.api.post("upload/delete", { id: file.id }, res => {
                    this.value.splice(index, 1);
                });
            },
            handleFormatError (file) {
                this.$Notice.warning({
                    title: '错误文件类型',
                    desc: '文件' + file.name + ' 格式错误，支持文件格式为' + this.format.join(",")
                });
            }
        },
        created() {
        }
    }
</script>
